package com.javajun.controller;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.javajun.custom.JqGridParm;
import com.javajun.custom.JqGridUtils;
import com.javajun.entity.Empower;
import com.javajun.entity.Enterprise;
import com.javajun.entity.EnterpriseAdmin;
import com.javajun.form.JEnterpriseForm;
import com.javajun.service.EnterpriseAdminService;
import com.javajun.service.EnterpriseService;
import com.javajun.service.UserRoleService;

/**
 * @className: EnterpriseController
 * @description: 
 * @author: JavaJun
 * @date: 2018年11月1日
 */
@Controller
@RequestMapping(value="/enterprise")
public class EnterpriseController {

    @Autowired
    private EnterpriseService enterpriseService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private EnterpriseAdminService enterpriseAdminService;
    private BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
    
    @RequestMapping(value="/manage", method=RequestMethod.GET)
    public String manage(ModelMap map) {
        return "enterprise/manage";
    }
    
    @RequestMapping(value="/home", method=RequestMethod.GET)
    public String home() {
        return "enterprise/home";
    }
    
    @RequestMapping(value = "getlist", method=RequestMethod.POST)
    // 返回json数据
    @ResponseBody
    public Object getList(JqGridParm parm) {
        Pageable pageable = parm.buildPageable();
        Page<Enterprise> page = null;
        if (!parm.getSearch()) {
            page = enterpriseService.findAll(pageable);
        } else {
            page = enterpriseService.findAll(parm.buildSpec(), pageable);
        }
        HashMap<String, Object> pageResult = JqGridUtils.getPageResult(page);
        return pageResult;
    }
    
    @RequestMapping(value = { "/add", "/edit" }, method = RequestMethod.POST)
    @ResponseBody
    public Object addAndEdit(ModelMap map, String[] id, JEnterpriseForm form) {
        // DateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        DateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd");// 将时间格式化 
        // BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        Enterprise entity = new Enterprise();
        // 实例化一个 Empower 授权类，如果租户中没有授权，则将其赋值给租户
        Empower empower = new Empower();
        if (entity.getEmpower() == null) {
            entity.setEmpower(empower);
        }
        String mess = "";
        if (form.getOper().equals("add")) {
            Integer enterpriseId = null;
            save(enterpriseId, form);
            mess = "Add is OK!";
        } else if (form.getOper().equals("edit")) {
            Integer enterpriseId = null;
            for (int i = 0; i < id.length; i++) {
                System.out.println(id[i]);
                enterpriseId = Integer.parseInt(id[i]);
            }
            save(enterpriseId, form);
        } else if (form.getOper().equals("del")) {
            for (int i = 0; i < id.length; i++) {
                delete(map, Integer.parseInt(id[i]));
                System.out.println("删除用户id：" + id[i]);
            }
            mess = "Delete is OK!";
        }
        return mess;
    }

    /**
     * Save 新增则传入一个不为空的id，以及一个 Enterprise 的表单对象
     * Save 修改则传入一个空的id，以及一个 Enterprise 的表单对象
     * @param id
     * @param entity
     */
    private void save(Integer id, JEnterpriseForm entity) {

        // 时间格式化格式
        SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd");
        
        Enterprise enterprise = new Enterprise();
        // 获取租户相关
        // 1.根据Id获取租户
        // 2.获取租户名字
        if (id != null) {
            enterprise = enterpriseService.findById(id);
            if(enterprise.getEnterpriseAdmin() == null) { // 当租户没有租户管理员时
                EnterpriseAdmin enterpriseAdmin = new EnterpriseAdmin();
                enterprise.setEnterpriseAdmin(enterpriseAdmin);
                enterprise.getEnterpriseAdmin().setPassword(encoder.encode("1111"));
                if (enterprise.getEnterpriseAdmin().getRoles() == null) {
                    enterprise.getEnterpriseAdmin().getRoles().add(userRoleService.findByCode("ROLE_ENTERPRISEADMIN"));
                }
            }
        }
        if (id == null) {
            Empower empower = new Empower();
            enterprise.setEmpower(empower);
            EnterpriseAdmin enterpriseAdmin = new EnterpriseAdmin();
            enterprise.setEnterpriseAdmin(enterpriseAdmin);
            enterprise.getEnterpriseAdmin().setPassword(encoder.encode("1111"));
            enterprise.getEnterpriseAdmin().getRoles().add(userRoleService.findByCode("ROLE_ENTERPRISEADMIN"));
        }
        if (StringUtils.hasText(entity.getName())) {
            enterprise.setName(entity.getName());
        }
        
        // 获取授权信息
        // 1.授权起始时间
        // 2.授权结束时间
        // 3.授权金额
        
        // 授权起始时间
        if (StringUtils.hasText(entity.getEmpower().getFormatStartTime())) {
            Date time = null;
            try {
                time = timeFormat.parse(entity.getEmpower().getFormatStartTime());
                System.out.println("授权起始时间：" + time);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            enterprise.getEmpower().setStartTime(time);
        }
        // 授权结束时间
        if (StringUtils.hasText(entity.getEmpower().getFormatEndTime())) {
            Date time = null;
            try {
                time = timeFormat.parse(entity.getEmpower().getFormatEndTime());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            System.out.println("授权结束时间："+ time);
            enterprise.getEmpower().setEndTime(time);
        }
        // 授权金额
        if (entity.getEmpower().getPayMoney() != null) {
            enterprise.getEmpower().setPayMoney(entity.getEmpower().getPayMoney());
        }
        
        // 获取租户管理员信息
        // 1.管理员名字
        // 2.管理员邮箱
        // 3.管理员电话
        if (StringUtils.hasText(entity.getEnterpriseAdmin().getName())) {
            enterprise.getEnterpriseAdmin().setName(entity.getEnterpriseAdmin().getName());
        }
        // 管理员邮箱（修改邮箱的同时也会修改用户名）
        if (StringUtils.hasText(entity.getEnterpriseAdmin().getEmail())) {
            String email = entity.getEnterpriseAdmin().getEmail();
            System.out.println("修改的邮箱：" + email);
            enterprise.getEnterpriseAdmin().setEmail(email);
            enterprise.getEnterpriseAdmin().setUsername(email);
        }
        // 管理员电话
        if (StringUtils.hasText(entity.getEnterpriseAdmin().getTel())) {
            enterprise.getEnterpriseAdmin().setTel(entity.getEnterpriseAdmin().getTel());
        }
        
        if (id == null) {
            enterprise.getEnterpriseAdmin().setPassword(encoder.encode("1111"));
            enterprise.getEnterpriseAdmin().getRoles().add(userRoleService.findByCode("ROLE_ENTERPRISEADMIN"));
        }
        // 保存
        enterpriseService.save(enterprise);
    }

    /**
     * Delte 删除一个租户
     * @param map
     * @param id
     */
    private void delete(ModelMap map, Integer id) {
        if (id != null) {
            Enterprise entity = enterpriseService.findById(id);
            enterpriseService.delete(entity);
        }
    }
    
    @RequestMapping(value="/register", method=RequestMethod.GET)
    public String register(ModelMap map) {
        return "enterprise/register";
    }
    
    @RequestMapping(value="/register", method=RequestMethod.POST)
    public void register(JEnterpriseForm form) {
        
        // 租户相关
        // 1.租户名字
        Enterprise entity = new Enterprise();
        entity.setName(form.getName());
        
        // 租户管理员相关
        // 1.名字
        // 2.邮箱
        // 3.用户名（与邮箱一致）
        // 4.联系电话
        // 5.密码
        EnterpriseAdmin enterpriseAdmin = new EnterpriseAdmin();
        enterpriseAdmin.setName(form.getEnterpriseAdmin().getName());
        enterpriseAdmin.setEmail(form.getEnterpriseAdmin().getEmail());
        enterpriseAdmin.setUsername(form.getEnterpriseAdmin().getEmail());
        enterpriseAdmin.setTel(form.getEnterpriseAdmin().getTel());
        enterpriseAdmin.setPassword(encoder.encode(form.getEnterpriseAdmin().getPassword()));
        entity.setEnterpriseAdmin(enterpriseAdmin);
        
        // 授权相关（默认添加增加一年的授权）
        // 1.增加一年时间
        
        // 2.授权金额
        Empower empower = new Empower();
        Date date = new Date();
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        // 增加一年
        cal.add(Calendar.YEAR, 1);
        empower.setStartTime(date);
        empower.setEndTime(cal.getTime());
        empower.setPayMoney(0.0);
        entity.setEmpower(empower);
        
        // 保存entity
        enterpriseService.save(entity);
    }
    
    @RequestMapping(value="/checkemail")
    @ResponseBody
    public Boolean checkemail(String email) {
        EnterpriseAdmin entity = enterpriseAdminService.findByUsername(email);
        Boolean b = false;
        if (entity != null) {
            b = false;
        } else {
            b = true;
        }
        return b;
    }
}
